package com.wutianyi.jackson;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;

import com.wutianyi.jackson.User.Name;

public class StreamingReader
{
    public static void main(String[] args) throws JsonParseException, IOException
    {
        JsonFactory f = new JsonFactory();
        JsonParser jp = f.createJsonParser(new File("user-streaming-write.json"));
        User user = new User();
        jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)
        while (jp.nextToken() != JsonToken.END_OBJECT)
        {
            String fieldname = jp.getCurrentName();
            jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY
            if ("name".equals(fieldname))
            { // contains an object
                Name name = new Name();
                while (jp.nextToken() != JsonToken.END_OBJECT)
                {
                    String namefield = jp.getCurrentName();
                    jp.nextToken(); // move to value
                    if ("first".equals(namefield))
                    {
                        name.setFirst(jp.getText());
                    }
                    else if ("last".equals(namefield))
                    {
                        name.setLast(jp.getText());
                    }
                    else
                    {
//                        throw new IllegalStateException("Unrecognized field '" + fieldname + "'!");
                    }
                }
                user.setName(name);
            }
            else if ("gender".equals(fieldname))
            {
                user.setGender(User.Gender.valueOf(jp.getText()));
            }
            else if ("verified".equals(fieldname))
            {
                user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE);
            }
            else if ("userImage".equals(fieldname))
            {
                user.setUserImage(jp.getBinaryValue());
            }
            else
            {
                throw new IllegalStateException("Unrecognized field '" + fieldname + "'!");
            }
        }
        jp.close();
    }
}
